import { List, Tabs } from "antd"
import React, { useEffect, useState } from "react"
import { Link, RouteComponentProps, useHistory, useLocation, withRouter } from "react-router-dom"
import styles from './style.module.css'

const { TabPane } = Tabs;

interface navProps {
    label: string,
    value: string
}
interface itemProps {
    title: string,
    path: string
}

interface IProps extends RouteComponentProps {
    defaultK?: string
    nav: Array<navProps>,
    content: IDictionary<Array<itemProps>>
}

const ContentList: React.FC<IProps> = ({ nav, content, defaultK }) => {
    const history = useHistory();
    const { pathname, search, hash, key } = useLocation();
    const [defaultKey, setDefaultKey] = useState(defaultK);
    // 初始为开发文档
    useEffect(() => {
        const searVal = search.split("=");
        if (searVal.length > 1) {
            const k = searVal[1];
            if (Object.keys(content).includes(k)) {
                setDefaultKey(k);
            }
        }
    }, []);

    const tabClick = (
        activeKey: string
        // e: React.MouseEvent<Element, MouseEvent> | React.KeyboardEvent<Element>
    ) => {
        if (activeKey != defaultKey) {
            history.replace(`${pathname}?key=${activeKey}`);
            setDefaultKey(activeKey);
        }
    };

    return <>
        <Tabs activeKey={defaultKey} tabPosition="left" onTabClick={tabClick}>
            {nav.map((it) => (
                <TabPane tab={it.label} key={it.value}>
                    <List
                        dataSource={content[it.value]}
                        renderItem={(item: ContentItem, index) => (
                            <List.Item key={index}>
                                <Link to={item.path}>
                                    <span className={styles.item_list}>
                                        {index + 1}、{item.title}
                                    </span>
                                </Link>
                            </List.Item>
                        )}
                    />
                </TabPane>
            ))}
        </Tabs>
    </>
}

export default withRouter(ContentList) 